package com.iakuil.app.common.core.domain;

import com.iakuil.app.common.core.enums.Results;
import io.swagger.v3.oas.annotations.media.Schema;

/**
 * 通用API响应结果
 *
 * <p>统一封装的用户接口层响应结果。
 * <p>错误码应统一定义在{@link Results}枚举中。
 * <p>{@link #props}可以添加动态属性。
 *
 * @author Kai
 */
@Schema(description = "API响应结果")
public class Result<T> extends DynamicFields {
    public Result() {
    }

    @Schema(description = "状态码")
    private int code;
    @Schema(description = "描述信息")
    private String msg;
    @Schema(description = "响应数据")
    private T data;

    public Result(int code, String message) {
        this.code = code;
        this.msg = message;
    }

    public Result(int code, String message, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    public static <T> Result<T> success() {
        return Result.success(Results.SUCCESS.getMessage());
    }

    public static <T> Result<T> success(String msg) {
        return Result.success(msg, null);
    }

    public static <T> Result<T> success(T data) {
        return Result.success(Results.SUCCESS.getMessage(), data);
    }

    public static <T> Result<T> success(String msg, T data) {
        return new Result<>(Results.SUCCESS.getCode(), msg, data);
    }

    public static <T> Result<T> error() {
        return Result.error(Results.FAIL.getMessage());
    }

    public static <T> Result<T> error(String msg) {
        return Result.error(Results.FAIL.getCode(), msg);
    }

    public static <T> Result<T> error(int code) {
        return Result.error(code, Results.FAIL.getMessage());
    }

    public static <T> Result<T> error(int code, String msg) {
        return new Result<>(code, msg);
    }

    public static <T> Result<T> error(Results r, String msg) {
        return new Result<>(r.getCode(), msg);
    }

    public boolean isSuccess() {
        return code == Results.SUCCESS.getCode();
    }

    public Long getTs() {
        return System.currentTimeMillis() / 1000;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}
